<template>
  <div
    class="min-h-screen bg-gradient-to-br from-green-50 via-emerald-50 to-teal-50 flex items-center justify-center p-4"
  >
    <div class="w-full max-w-md">
      <!-- Logo/标题区域 -->
      <div class="text-center mb-8">
        <div
          class="mx-auto w-16 h-16 bg-gradient-to-br from-green-500 to-teal-600 rounded-2xl flex items-center justify-center mb-4 shadow-lg"
        >
          <Icon name="user" size="32" class="text-white" />
        </div>
        <h1 class="text-3xl font-bold text-gray-900 mb-2">创建新账户</h1>
        <p class="text-gray-600">加入我们，开始您的AI对话之旅</p>
      </div>

      <!-- 注册表单卡片 -->
      <div class="bg-white rounded-2xl shadow-xl border border-gray-100 p-8">
        <h2 class="text-xl font-semibold text-gray-900 mb-6 text-center">用户注册</h2>

        <form @submit.prevent="handleRegister" class="space-y-6">
          <!-- 用户名输入 -->
          <div class="form-group">
            <label class="form-label">用户名</label>
            <input
              v-model="registerForm.username"
              type="text"
              placeholder="请输入用户名"
              class="input"
              :class="{ 'input-error': errors.username }"
              @blur="validateField('username')"
            />
            <span v-if="errors.username" class="form-error">{{ errors.username }}</span>
          </div>

          <!-- 邮箱输入 -->
          <div class="form-group">
            <label class="form-label">邮箱</label>
            <input
              v-model="registerForm.email"
              type="email"
              placeholder="请输入邮箱地址"
              class="input"
              :class="{ 'input-error': errors.email }"
              @blur="validateField('email')"
            />
            <span v-if="errors.email" class="form-error">{{ errors.email }}</span>
          </div>

          <!-- 昵称输入 -->
          <div class="form-group">
            <label class="form-label">昵称 <span class="text-gray-400 text-sm">(可选)</span></label>
            <input
              v-model="registerForm.nickname"
              type="text"
              placeholder="请输入昵称"
              class="input"
            />
          </div>

          <!-- 密码输入 -->
          <div class="form-group">
            <label class="form-label">密码</label>
            <div class="relative">
              <input
                v-model="registerForm.password"
                :type="showPassword ? 'text' : 'password'"
                placeholder="请输入密码"
                class="input pr-12"
                :class="{ 'input-error': errors.password }"
                @blur="validateField('password')"
              />
              <button
                type="button"
                @click="showPassword = !showPassword"
                class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600 transition-colors"
              >
                <Icon :name="showPassword ? 'eye-off' : 'eye'" size="20" />
              </button>
            </div>
            <span v-if="errors.password" class="form-error">{{ errors.password }}</span>
          </div>

          <!-- 确认密码输入 -->
          <div class="form-group">
            <label class="form-label">确认密码</label>
            <div class="relative">
              <input
                v-model="registerForm.confirmPassword"
                :type="showConfirmPassword ? 'text' : 'password'"
                placeholder="请再次输入密码"
                class="input pr-12"
                :class="{ 'input-error': errors.confirmPassword }"
                @blur="validateField('confirmPassword')"
                @keyup.enter="handleRegister"
              />
              <button
                type="button"
                @click="showConfirmPassword = !showConfirmPassword"
                class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600 transition-colors"
              >
                <Icon :name="showConfirmPassword ? 'eye-off' : 'eye'" size="20" />
              </button>
            </div>
            <span v-if="errors.confirmPassword" class="form-error">{{
              errors.confirmPassword
            }}</span>
          </div>

          <!-- 注册按钮 -->
          <button
            type="submit"
            :disabled="loading || !isFormValid"
            class="btn-primary w-full py-3 text-base font-medium disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <div v-if="loading" class="flex items-center justify-center">
              <div class="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2"></div>
              注册中...
            </div>
            <span v-else>创建账户</span>
          </button>
        </form>

        <!-- 底部链接 -->
        <div class="mt-6 pt-6 border-t border-gray-200 text-center">
          <button @click="$router.push('/login')" class="btn-text text-sm">
            已有账户？立即登录
          </button>
        </div>
      </div>

      <!-- 底部信息 -->
      <div class="text-center mt-8 text-sm text-gray-500">
        <p>© 2024 AI 对话助手. 保留所有权利.</p>
      </div>
    </div>
  </div>
</template>

<script>
import { computed, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import Icon from '../components/icons/Icon.vue'

export default {
  name: 'Register',
  components: {
    Icon,
  },
  setup() {
    const store = useStore()
    const router = useRouter()

    const loading = ref(false)
    const showPassword = ref(false)
    const showConfirmPassword = ref(false)

    const registerForm = reactive({
      username: '',
      email: '',
      nickname: '',
      password: '',
      confirmPassword: '',
    })

    const errors = reactive({
      username: '',
      email: '',
      password: '',
      confirmPassword: '',
    })

    const rules = {
      username: [
        { required: true, message: '请输入用户名' },
        { min: 3, max: 50, message: '用户名长度在 3 到 50 个字符' },
      ],
      email: [
        { required: true, message: '请输入邮箱地址' },
        { type: 'email', message: '请输入有效的邮箱地址' },
      ],
      password: [
        { required: true, message: '请输入密码' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符' },
      ],
      confirmPassword: [{ required: true, message: '请确认密码' }],
    }

    const isFormValid = computed(() => {
      return (
        registerForm.username.trim() &&
        registerForm.email.trim() &&
        registerForm.password.trim() &&
        registerForm.confirmPassword.trim() &&
        !errors.username &&
        !errors.email &&
        !errors.password &&
        !errors.confirmPassword
      )
    })

    const validateField = (field) => {
      const value = registerForm[field]
      const fieldRules = rules[field]

      for (const rule of fieldRules) {
        if (rule.required && !value.trim()) {
          errors[field] = rule.message
          return false
        }

        if (rule.type === 'email' && value.trim()) {
          const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
          if (!emailRegex.test(value)) {
            errors[field] = rule.message
            return false
          }
        }

        if (rule.min && value.length < rule.min) {
          errors[field] = rule.message
          return false
        }

        if (rule.max && value.length > rule.max) {
          errors[field] = rule.message
          return false
        }
      }

      // 特殊验证：确认密码
      if (field === 'confirmPassword' && value !== registerForm.password) {
        errors[field] = '两次输入的密码不一致'
        return false
      }

      errors[field] = ''
      return true
    }

    const validateForm = () => {
      let isValid = true
      Object.keys(rules).forEach((field) => {
        if (!validateField(field)) {
          isValid = false
        }
      })
      return isValid
    }

    const handleRegister = async () => {
      if (!validateForm()) return

      try {
        loading.value = true

        await store.dispatch('register', {
          username: registerForm.username,
          email: registerForm.email,
          nickname: registerForm.nickname,
          password: registerForm.password,
        })

        showSuccessMessage('注册成功，请登录')
        router.push('/login')
      } catch (error) {
        console.error('Register error:', error)
        showErrorMessage(error.message || '注册失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }

    const showSuccessMessage = (message) => {
      if (window.$toast) {
        window.$toast.success(message)
      }
    }

    const showErrorMessage = (message) => {
      if (window.$toast) {
        window.$toast.error(message)
      }
    }

    return {
      loading,
      showPassword,
      showConfirmPassword,
      registerForm,
      errors,
      isFormValid,
      validateField,
      handleRegister,
    }
  },
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.register-form {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

.register-form h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.form-links {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
